package cn.com.cifi.mars.web.action.report;

import cn.com.cifi.mars.bean.bo.SysLogBO;
import cn.com.cifi.mars.bean.dto.ProjectByStagesDto;
import cn.com.cifi.mars.bean.vo.returnPlan.returnReport.ReturnPlanProgressVo;
import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.*;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.service.ReturnPlanProgressBaseService;
import cn.com.cifi.mars.service.SysLogService;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.ReturnPlanProgressTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
public class ReturnPlanProgressController extends BaseAction implements IReturnPlanProgessController {

    @Autowired
    private ReturnPlanProgressBaseService returnPlanProgressBaseService;
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private IdmUserService idmUserService;

    @Override
    public R returnPlanProgress(String apiVersion, String yearMonth, String name, String versionStatus, String startTime, String endTime) {
        saveLog(LogEventEnum.BROWSE, "回款计划进度表", "回款计划进度表", startTime + ":" + endTime);
        //查询用户权限项目id列表
        List<String> projectIdList = prepareUserDataPermission(getOperator().getUsername());
        if (CollectionUtils.isEmpty(projectIdList)) {
            throw new MsgException(CodeEnum.NOT_PROJECT_PERMISSIONS_ERROR);
        }

        List<ReturnPlanProgressVo> list = returnPlanProgressBaseService.getReturnPlanProgressList(yearMonth, projectIdList, name, versionStatus, startTime, endTime);
        return ok(list);
    }

    /**
     * 回款计划进度表导出
     *
     * @param apiVersion
     * @param response
     * @param yearMonth
     */
    @Override
    public void returnPlanProgressExport(String apiVersion, HttpServletResponse response, String yearMonth) {
        //获取用户权限下可查看的项目列表
        List<String> projectIdList = prepareUserDataPermission(getOperator().getUsername());
        if (CollectionUtils.isEmpty(projectIdList)) {
            throw new MsgException(CodeEnum.NOT_PROJECT_PERMISSIONS_ERROR);
        }
        List<ReturnPlanProgressVo> list = returnPlanProgressBaseService.getReturnPlanProgressList(yearMonth, projectIdList, null, null, null, null);
        
        //编辑表名
        String name = "回款计划进度表-" + yearMonth.replace("-", "") + "-" + LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyyMMddHH");
        ReturnPlanProgressTemplate returnPlanProgressTemplate = new ReturnPlanProgressTemplate(name);
        returnPlanProgressTemplate.appendRows(list);
        try (OutputStream outputStream = response.getOutputStream()) {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name.concat(".xlsx"), "utf-8"));
            returnPlanProgressTemplate.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("###### errorMsg: ", e);
        }
    }

    /**
     * 手动刷新符合条件的回款计划列表
     *
     * @param apiVersion
     * @return
     */
    @Override
    public R refreshSignPlanProgress(String apiVersion) {
        returnPlanProgressBaseService.refresh();
        return ok("刷新成功");
    }

    /**
     * 查询用户的权限项目
     *
     * @param userName
     * @return
     */
    private List<String> prepareUserDataPermission(String userName) {
        List<String> projectIds = Collections.synchronizedList(new ArrayList<>());
        List<ProjectByStagesDto> dataPermissionList = idmUserService.queryUserDataPermissions(userName);
        if (CollectionUtils.isNotEmpty(dataPermissionList)) {
            for (ProjectByStagesDto dto : dataPermissionList) {
                if (dto.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_31.getKey())) {
                    projectIds.add(dto.getOrgdepid());
                }
            }
        }
        return projectIds;
    }

    /**
     * 保存系统日志
     */
    private boolean saveLog(LogEventEnum logEventEnum, String module, String title, String content) {
        SysLogBO bo = new SysLogBO();
        bo.setEvent(logEventEnum);
        bo.setSource(LogSrcEnum.PC);
        bo.setModule(module);
        bo.setTitle(title);
        bo.setContent(content);
        bo.setType(LogTypeEnum.ONE.getKey());
        bo.setIsSuccess(IsSuccessEnum.SUCCESS.getKey());
        return sysLogService.add(bo, Constants.SYS);
    }
}
